package com.cdvtc.fengchao.Servlet;

import com.alibaba.fastjson.JSONObject;
import com.cdvtc.fengchao.dao.ProductsDAO;
import com.cdvtc.fengchao.model.CartItem;
import com.cdvtc.fengchao.model.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebServlet("/cart/*")
public class CartServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private ProductsDAO productsDAO;

    // 提取价格的正则表达式
    private static final Pattern PRICE_PATTERN = Pattern.compile("[0-9]+(\\.[0-9]+)?");

    @Override
    public void init() throws ServletException {
        super.init();
        productsDAO = new ProductsDAO();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 添加详细的请求信息日志
        System.out.println("CartServlet doGet - RequestURL: " + request.getRequestURL().toString());
        System.out.println("CartServlet doGet - PathInfo: " + request.getPathInfo());
        System.out.println("CartServlet doGet - QueryString: " + request.getQueryString());
        System.out.println("CartServlet doGet - productId: " + request.getParameter("productId"));
        System.out.println("CartServlet doGet - quantity: " + request.getParameter("quantity"));

        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");

        // 添加详细的请求信息日志
        System.out.println("\n--- CartServlet Request Start ---");
        System.out.println("CartServlet doPost - RequestURL: " + request.getRequestURL().toString());
        System.out.println("CartServlet doPost - PathInfo: " + request.getPathInfo());
        System.out.println("CartServlet doPost - QueryString: " + request.getQueryString());
        System.out.println("CartServlet doPost - ContentType: " + request.getContentType());
        System.out.println("CartServlet doPost - productId: " + request.getParameter("productId"));
        System.out.println("CartServlet doPost - quantity: " + request.getParameter("quantity"));

        PrintWriter out = response.getWriter();
        String action = request.getPathInfo();
        Map<String, Object> result = new HashMap<>();

        System.out.println("CartServlet - Action: " + action);
        System.out.println("CartServlet - Request URI: " + request.getRequestURI());

        try {
            if ("/add".equals(action)) {
                System.out.println("Handling /add action");
                handleAddToCart(request, result);
            } else if ("/update".equals(action)) {
                System.out.println("Handling /update action");
                handleUpdateCart(request, result);
            } else if ("/delete".equals(action)) {
                System.out.println("Handling /delete action");
                handleDeleteFromCart(request, result);
            } else if ("/count".equals(action)) {
                System.out.println("Handling /count action");
                handleGetCartCount(request, result);
            } else {
                System.out.println("Unknown action: " + action);
                result.put("success", false);
                result.put("message", "未知操作: " + action);
            }
        } catch (Exception e) {
            System.err.println("Error in CartServlet:");
            e.printStackTrace(System.err);
            result.put("success", false);
            result.put("message", "服务器错误: " + e.getMessage());
        }

        // 添加响应日志
        System.out.println("CartServlet Response: " + JSONObject.toJSONString(result));
        System.out.println("--- CartServlet Request End ---\n");

        String jsonResult = JSONObject.toJSONString(result);
        out.println(jsonResult);
        out.flush();
    }

    // 处理添加到购物车
    private void handleAddToCart(HttpServletRequest request, Map<String, Object> result) {
        try {
            String productIdStr = request.getParameter("productId");
            String quantityStr = request.getParameter("quantity");

            System.out.println("handleAddToCart - Parameters: productId=" + productIdStr + ", quantity=" + quantityStr);

            if (productIdStr == null || productIdStr.trim().isEmpty()) {
                System.err.println("Error: productId is empty");
                result.put("success", false);
                result.put("message", "参数错误: 商品ID不能为空");
                return;
            }

            if (quantityStr == null || quantityStr.trim().isEmpty()) {
                System.err.println("Error: quantity is empty");
                result.put("success", false);
                result.put("message", "参数错误: 数量不能为空");
                return;
            }

            int productId;
            int quantity;

            try {
                productId = Integer.parseInt(productIdStr.trim());
                quantity = Integer.parseInt(quantityStr.trim());
            } catch (NumberFormatException e) {
                System.err.println("Error parsing numbers: " + e.getMessage());
                result.put("success", false);
                result.put("message", "参数错误: 请确保商品ID和数量为数字");
                return;
            }

            if (productId <= 0) {
                System.err.println("Error: productId <= 0");
                result.put("success", false);
                result.put("message", "参数错误: 商品ID必须大于0");
                return;
            }

            if (quantity <= 0) {
                System.err.println("Error: quantity <= 0");
                result.put("success", false);
                result.put("message", "参数错误: 数量必须大于0");
                return;
            }

            System.out.println("Parsed parameters: productId=" + productId + ", quantity=" + quantity);

            Product product = productsDAO.getProductById(productId);
            if (product == null) {
                System.err.println("Product not found: " + productId);
                result.put("success", false);
                result.put("message", "产品不存在 (ID: " + productId + ")");
                return;
            }

            System.out.println("Found product: " + product.getName());

            HttpSession session = request.getSession(true);
            @SuppressWarnings("unchecked")
            Map<Integer, CartItem> cart = (Map<Integer, CartItem>) session.getAttribute("cart");

            if (cart == null) {
                cart = new HashMap<>();
                session.setAttribute("cart", cart);
                System.out.println("Created new cart");
            }

            if (cart.containsKey(productId)) {
                CartItem item = cart.get(productId);
                item.setQuantity(item.getQuantity() + quantity);
                System.out.println("Updated item quantity: " + item.getQuantity());
            } else {
                String rawPrice = product.getPrice();
                System.out.println("Raw price: " + rawPrice);

                if (rawPrice == null || rawPrice.trim().isEmpty()) {
                    System.err.println("Error: price is empty");
                    result.put("success", false);
                    result.put("message", "商品价格信息不完整");
                    return;
                }

                Matcher matcher = PRICE_PATTERN.matcher(rawPrice);
                if (!matcher.find()) {
                    System.err.println("Error: price format invalid - " + rawPrice);
                    result.put("success", false);
                    result.put("message", "价格格式错误: " + rawPrice);
                    return;
                }

                BigDecimal price;
                try {
                    price = new BigDecimal(matcher.group(0));
                    System.out.println("Parsed price: " + price);
                } catch (NumberFormatException e) {
                    System.err.println("Error converting price: " + matcher.group(0));
                    result.put("success", false);
                    result.put("message", "价格转换失败: " + matcher.group(0));
                    return;
                }

                CartItem item = new CartItem(productId, product.getName(), price, quantity, product);
                cart.put(productId, item);
                System.out.println("Added new item to cart");
            }

            int cartCount = getCartItemCount(cart);
            System.out.println("Cart item count: " + cartCount);

            result.put("success", true);
            result.put("message", "已添加到购物车");
            result.put("cartCount", String.valueOf(cartCount));

        } catch (Exception e) {
            System.err.println("Error in handleAddToCart:");
            e.printStackTrace(System.err);
            result.put("success", false);
            result.put("message", "添加失败: " + e.getMessage());
        }
    }

    // 处理更新购物车
    private void handleUpdateCart(HttpServletRequest request, Map<String, Object> result) {
        try {
            String productIdStr = request.getParameter("productId");
            String quantityStr = request.getParameter("quantity");

            System.out.println("handleUpdateCart - Parameters: productId=" + productIdStr + ", quantity=" + quantityStr);

            if (productIdStr == null || productIdStr.trim().isEmpty() ||
                    quantityStr == null || quantityStr.trim().isEmpty()) {
                System.err.println("Error: parameters are empty");
                result.put("success", false);
                result.put("message", "参数错误: 商品ID和数量不能为空");
                return;
            }

            int productId = Integer.parseInt(productIdStr.trim());
            int quantity = Integer.parseInt(quantityStr.trim());

            HttpSession session = request.getSession(false);
            if (session == null) {
                System.err.println("Error: session is null");
                result.put("success", false);
                result.put("message", "购物车不存在");
                return;
            }

            @SuppressWarnings("unchecked")
            Map<Integer, CartItem> cart = (Map<Integer, CartItem>) session.getAttribute("cart");
            if (cart == null) {
                System.err.println("Error: cart is null");
                result.put("success", false);
                result.put("message", "购物车为空");
                return;
            }

            if (cart.containsKey(productId)) {
                if (quantity <= 0) {
                    cart.remove(productId);
                    System.out.println("Removed item from cart");
                } else {
                    CartItem item = cart.get(productId);
                    if (quantity > item.getProduct().getStock()) {
                        System.err.println("Error: insufficient stock");
                        result.put("success", false);
                        result.put("message", "商品库存不足，无法更新数量！");
                        return;
                    }
                    item.setQuantity(quantity);
                    System.out.println("Updated item quantity: " + quantity);
                }
                result.put("success", true);
                result.put("message", "购物车更新成功");
                result.put("cartCount", String.valueOf(getCartItemCount(cart)));
            } else {
                System.err.println("Error: product not in cart");
                result.put("success", false);
                result.put("message", "购物车中不存在该商品");
            }
        } catch (Exception e) {
            System.err.println("Error in handleUpdateCart:");
            e.printStackTrace(System.err);
            result.put("success", false);
            result.put("message", "更新失败: " + e.getMessage());
        }
    }

    // 处理从购物车删除商品
    private void handleDeleteFromCart(HttpServletRequest request, Map<String, Object> result) {
        try {
            String productIdStr = request.getParameter("productId");
            System.out.println("handleDeleteFromCart - Parameters: productId=" + productIdStr);

            if (productIdStr == null || productIdStr.trim().isEmpty()) {
                System.err.println("Error: productId is empty");
                result.put("success", false);
                result.put("message", "参数错误: 商品ID不能为空");
                return;
            }
            int productId = Integer.parseInt(productIdStr.trim());

            HttpSession session = request.getSession(false);
            if (session == null) {
                System.err.println("Error: session is null");
                result.put("success", false);
                result.put("message", "购物车不存在");
                return;
            }

            @SuppressWarnings("unchecked")
            Map<Integer, CartItem> cart = (Map<Integer, CartItem>) session.getAttribute("cart");
            if (cart == null) {
                System.err.println("Error: cart is null");
                result.put("success", false);
                result.put("message", "购物车为空");
                return;
            }

            if (cart.containsKey(productId)) {
                cart.remove(productId);
                System.out.println("Item removed from cart");
                result.put("success", true);
                result.put("message", "商品已从购物车删除");
                result.put("cartCount", String.valueOf(getCartItemCount(cart)));
            } else {
                System.err.println("Error: product not in cart");
                result.put("success", false);
                result.put("message", "购物车中不存在该商品");
            }
        } catch (NumberFormatException e) {
            System.err.println("Error: invalid productId format");
            result.put("success", false);
            result.put("message", "参数错误: 商品ID必须为数字");
        } catch (Exception e) {
            System.err.println("Error in handleDeleteFromCart:");
            e.printStackTrace(System.err);
            result.put("success", false);
            result.put("message", "删除失败: " + e.getMessage());
        }
    }

    // 处理获取购物车商品数量
    private void handleGetCartCount(HttpServletRequest request, Map<String, Object> result) {
        System.out.println("handleGetCartCount");
        HttpSession session = request.getSession(false);
        if (session == null) {
            System.out.println("Session is null, cartCount=0");
            result.put("success", true);
            result.put("cartCount", "0");
            return;
        }

        @SuppressWarnings("unchecked")
        Map<Integer, CartItem> cart = (Map<Integer, CartItem>) session.getAttribute("cart");
        if (cart == null) {
            System.out.println("Cart is null, cartCount=0");
            result.put("success", true);
            result.put("cartCount", "0");
        } else {
            int count = getCartItemCount(cart);
            System.out.println("Cart count: " + count);
            result.put("success", true);
            result.put("cartCount", String.valueOf(count));
        }
    }

    // 计算购物车商品总数
    private int getCartItemCount(Map<Integer, CartItem> cart) {
        int count = 0;
        for (CartItem item : cart.values()) {
            count += item.getQuantity();
        }
        return count;
    }
}